const httpResult = require("../lib/httpResult");
const _ = require("lodash");
let router = require('koa-router')();
let moment = require('moment');
const MyEmitter = require('../lib/MyEmitter');
const utils = require('../lib/utils');

let match = new MyEmitter(10, matchReport, async (result) => {console.log(result)});
match.name = 'report_match_thread';
match.startup();

let moMatch = new MyEmitter(10, matchMo, async (result) => {console.log(result)});
moMatch.name = 'mo_match_thread';
moMatch.startup();

/**
 * hexingtx sms channel api，accept report
 */
router.post('/report', httpResult.respRaw(async (ctx) => {
  let data = ctx.request.body;

  let reports = await models.mtReport.create({
    uid : data.msgId,
    phone : data.phone,
    appkey : '',
    status : data.status,
    desc : data.status == 1 ? 'DELIVRD' : 'UNDELIV',
    report_time : moment().format('YYYY-MM-DD HH:mm:ss')
  });
  console.log(reports)
  match.addTask(reports);
  return {
    code : '00000'
  }
}));

/**
 * hexingtx sms channel api，accept deliver message
 */
router.post('/mo', httpResult.respRaw(async (ctx) => {
  let data = ctx.request.body;
  console.log(data)
  let mo = await models.moMsg.create(data);
  moMatch.addTask(mo);
  return {
    code : '00000'
  }
}));

function feeCount(content){
  if(content.length <= 70){
    return 1;
  }else{
    return Math.ceil(content.length / 67)
  }
}

async function matchReport(r) {
  let cReports = [];
  let q = {mt_msg_id: r.uid, mobile: r.phone};
  let update = {
    report_status: r.status,
    report_desc: r.event,
    report_time: new Date()
  }
  let mt = await models.mtMsg.findOneAndUpdate(q, update);

  if (mt) {
    cReports.push({
      msg_id: mt._id,
      mobile: r.phone,
      status: r.desc,
      report_date: moment(update.report_time).format('YYYY-MM-DD HH:mm:ss'),
      send_date: moment(mt.send_time).format('YYYY-MM-DD HH:mm:ss'),
      pieces: mt.charge_count,
      ext: mt.ext,
      ticket: mt.request_id,
      ref: mt.ref,
      cus_id: mt.account,
      iso_code : utils.getIsoCodeByNumber(r.phone)
    })
  }
  let saveResults = await models.customerReport.create(cReports);
  // console.log(saveResults);
}

async function matchMo(m) {
  let cMo = [];
  // let mt = await models.mtMsg.findOne({mobile: m.phone})
  // if (mt) {
    cMo.push({
      mobiles: m.phone,
      mo_date: m.deliver_time,
      content: m.msg,
      ext: m.extend,
      cus_id: m.appkey
    })
  // }
  await models.customerMo.create(cMo);
}

module.exports = router;
